package org.summerframework.component.security.core.util.useragent;

import jdk.nashorn.api.scripting.ScriptObjectMirror;
import lombok.extern.slf4j.Slf4j;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.InputStreamReader;

@Slf4j
public final class UADeviceJsUtil {
    private static Invocable invoke;

    static {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine scriptEngine = manager.getEngineByName("javascript");

        try {
            scriptEngine.eval(new InputStreamReader(UADeviceJsUtil.class.getClassLoader().getResourceAsStream("uaDevice/ua-device.js")));
            scriptEngine.eval(new InputStreamReader(UADeviceJsUtil.class.getClassLoader().getResourceAsStream("uaDevice/useragent-base.js")));

            if (scriptEngine instanceof Invocable) {
                invoke = (Invocable) scriptEngine;    // 调用merge方法，并传入两个参数
            }
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

    public static UserAgentInfo parse(String ua) {
        ScriptObjectMirror scriptObjectMirror = null;

        try {
            scriptObjectMirror = (ScriptObjectMirror) invoke.invokeFunction("uaDevice", ua);
        } catch (NoSuchMethodException | ScriptException e) {
            log.debug("UserAgentInfo error", e);
        }

        return new UserAgentInfo(scriptObjectMirror);
    }
}
